<?php

namespace app\admin\model;


use app\company\model\CompanyDividend;
use Exception;

/**
 * 公司
 * @property int $id
 * @property string $name 公司名称
 */
class Company extends Base
{
    /**
     * 搜索器  名称/id
     * @param $query
     * @param $value
     * @param $data
     * @return void
     */
    public function searchNameAttr($query, $value, $data): void
    {
        if ($value) $query->where('name', 'like', '%' . $value . '%')->whereOr('id', 'like', '%' . $value . '%');
    }

    public static function onAfterInsert(Company $model)
    {
        $param = request()->param();
        //添加用户
        $user                = new CompanyUser();
        $param['company_id'] = $model->id;
        $user->save($param);
        //创建完成后添加一个admin_user 进行分红关联
        $adminUser = AdminUser::create([
            'user_name' => $param['user_name'],
            'password'  => md5(rand(10000, 99999) . rand(10000, 99999)),
            'real_name' => $param['real_name'],
            'mobile'    => $param['mobile'],
            'identity'  => 5
        ]);
        //添加分成配置
        $dividend               = request()->only(['investor_id', 'investor_ratio', 'service_id', 'service_ratio']);
        $dividend['company_id'] = $model->id;
        $dividend['partner_id'] = $adminUser->id;
        CompanyDividend::create($dividend);
        //添加小程序配置
        ConfigMini::create(['company_id' => $model->id]);

    }


    /**
     * @throws Exception
     */
    public static function onBeforeUpdate(Company $model)
    {
        $param = request()->param();
        //修改用户
        if (isset($param['user_name']) || isset($param['password']) || isset($param['mobile']) || isset($param['real_name'])) {
            $user = (new CompanyUser())->admin()->where('company_id', $param['id'])->find();
            if (isset($param['mobile'])) {
                if ((new CompanyUser())->where('user_name', $param['user_name'])->whereNotIn('id', $user->id)->value('id')) exception('用户名已存在');
            }
            unset($param['id']);
            $user->save($param);
        }

        //修改分红信息
        if (isset($param['investor_id']) || isset($param['investor_ratio']) || isset($param['service_id']) || isset($param['service_ratio'])) {
            $user = (new CompanyDividend())->where('company_id', request()->param('id', 0))->find();
            if (isset($param['id'])) unset($param['id']);
            $user->save($param);
        }
    }

    /**
     * 删除前事件
     * @param Company $model
     * @return void
     */
    public static function onBeforeDelete(Company $model): void
    {
        $model->companyUsers->delete();
    }
}